package com.wx.spider.mobile.controller;

import com.wx.spider.common.model.AppmsgParamsModel;
import com.wx.spider.common.model.CommonResponse;
import com.wx.spider.common.model.Constants;
import com.wx.spider.mobile.config.CloudConfig;
import com.wx.spider.mobile.service.AppmsgService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @author:feng
 * @create:2021-04-26 17:20
 */
@RestController
@RequestMapping("/appmsg")
@Slf4j
public class AppmsgController {
    @Autowired
    private CloudConfig cloudConfig;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private AppmsgService appmsgService;

    /**
     * 获取抓包结果
     * @return
     */
    @RequestMapping(value = "/pushAppmsg", method = RequestMethod.POST, produces="application/json")
    @CrossOrigin(origins = "*",maxAge = 3600)
    private CommonResponse<String> pushAppmsg(@RequestBody AppmsgParamsModel appmsgParamsModel){
        try {

            if(appmsgParamsModel.getCookies() == null || appmsgParamsModel.getReferer() == null || appmsgParamsModel.getUrl() == null){
                return CommonResponse.SUCCESS_RESPONSE;
            }

            appmsgService.getAppMsg(appmsgParamsModel);

            return CommonResponse.SUCCESS_RESPONSE;
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResponse.INTERNAL_ERROR_RESPONSE;
        }
    }

    /**
     * 获取任务
     * @return
     */
    @GetMapping("/appmsgBizTask")
    @CrossOrigin(origins = "*",maxAge = 3600)
    private CommonResponse<Map<String, String>> appmsgBizTask(){
        try {

            String url = null;
            while (stringRedisTemplate.opsForList().size(Constants.WX_BIZ_GET_APPMSG_QUNUE) > 0) {
                url = stringRedisTemplate.opsForList().leftPop(Constants.WX_BIZ_GET_APPMSG_QUNUE);
                //双重校验
                if(url != null){
                    break;
                }
            }

            HashMap<String, String> map = new HashMap<>();

            if (url == null) {
                map.put("msg","noTask");
            }else{
                map.put("url", url);
            }

            return CommonResponse.succeed(map);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResponse.INTERNAL_ERROR_RESPONSE;
        }
    }

    /**
     * 获取随机睡眠时间
     * @return
     */
    @GetMapping("/randomSleepTime")
    @CrossOrigin(origins = "*",maxAge = 3600)
    private CommonResponse<Integer> randomSleepTime(){
        try {
            Random random = new Random();
            Integer min = cloudConfig.getMinSleepTimeGetAppmsg() == null ? 5 : cloudConfig.getMinSleepTimeGetAppmsg();
            Integer max = cloudConfig.getMaxSleepTimeGetAppmsg() == null ? 10 : cloudConfig.getMaxSleepTimeGetAppmsg();

            return CommonResponse.succeed(random.nextInt(max - min) + min);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResponse.INTERNAL_ERROR_RESPONSE;
        }
    }

    /**
     * 获取剩余任务数和当前账号24小时内已执行的次数
     * @return
     */
    @GetMapping("/getQunueSize/{phone}")
    @CrossOrigin(origins = "*",maxAge = 3600)
    private CommonResponse<Map<String,Long>> getQunueSize(@PathVariable("phone") String phone){
        try {

            if (phone == null || "".equals(phone)){
                return CommonResponse.PARAM_ERROR_RESPONSE;
            }

            //判断当前账号24H内已执行页数
            String key = Constants.WX_BIZ_GET_APPMSG_ACCOUNT + phone;
            //获取24H前时间戳
            long before24H = System.currentTimeMillis() - (1000 * 60 * 60 * 24);
            //移除24H之前爬取的记录
            while(stringRedisTemplate.opsForList().size(key) > 0){
                Long value = Long.valueOf(stringRedisTemplate.opsForList().index(key, 0));
                if(value < before24H){
                    stringRedisTemplate.opsForList().leftPop(key);
                }else{
                    break;
                }
            }

            HashMap<String, Long> map = new HashMap<>();
            Long qunueSize = stringRedisTemplate.opsForList().size(Constants.WX_BIZ_GET_APPMSG_QUNUE);
            map.put("qunueSize", qunueSize);
            Long runCount = stringRedisTemplate.opsForList().size(key);
            map.put("runCount", runCount);

            return CommonResponse.succeed(map);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResponse.INTERNAL_ERROR_RESPONSE;
        }
    }
}
